package com.security.admin.controller;

import com.security.admin.handler.RestErrorHandler;
import com.security.admin.model.Credentials;
import com.security.admin.model.TokenInfo;
import com.security.admin.util.RestUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author yanggld
 * @Date 2020/3/12-10:21
 */
@CrossOrigin
@Slf4j
@RestController
public class AdminController {

    @Autowired
    private RestTemplate restTemplate;

    @PostMapping("/doLogin")
    public Map<String, Object> doLogin(@RequestBody Credentials credentials) {
        String oauthUrl = "http://localhost:6100/auth/oauth/token";
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        httpHeaders.setBasicAuth("admin", "123456");
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("username", credentials.getUsername());
        params.add("password", credentials.getPassword());
        params.add("grant_type", "password");
        params.add("scope", "read write");
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(params, httpHeaders);
        Map<String, Object> map = new HashMap<>();
        TokenInfo tokenInfo;
        try {
            ResponseEntity<TokenInfo> responseEntity =
                restTemplate.exchange(oauthUrl, HttpMethod.POST, httpEntity, TokenInfo.class);
            log.info("登录获取token:{}", responseEntity.getBody().toString());
            tokenInfo = responseEntity.getBody();
        } catch (Exception e) {
            log.error(e.getMessage());
            String result = RestUtil.getCause(restTemplate);
            throw new RuntimeException(result);
        }
        map.put("access_token", tokenInfo.getAccess_token());
        map.put("refresh_token", tokenInfo.getRefresh_token());
        return map;
    }

    @GetMapping("/token/refresh")
    public Map<String, Object> refresh(@RequestParam String refreshToken) {
        String oauthUrl = "http://localhost:6100/auth/oauth/token";
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        httpHeaders.setBasicAuth("admin", "123456");
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("grant_type", "refresh_token");
        params.add("refresh_token", refreshToken);
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(params, httpHeaders);
        Map<String, Object> map = new HashMap<>();
        TokenInfo tokenInfo;
        try {
            ResponseEntity<TokenInfo> responseEntity =
                restTemplate.exchange(oauthUrl, HttpMethod.POST, httpEntity, TokenInfo.class);
            log.info("refresh获取token:{}", responseEntity.getBody().toString());
            tokenInfo = responseEntity.getBody();
            tokenInfo.init();
        } catch (Exception e) {
            log.error(e.getMessage());
            String result = RestUtil.getCause(restTemplate);
            throw new RuntimeException(result);
        }
        map.put("access_token", tokenInfo.getAccess_token());
        map.put("refresh_token", tokenInfo.getRefresh_token());
        return map;
    }

}
